package com.xbongbong.workflow.service.strategy.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.executor.command.FormDataServiceFactory;
import com.xbongbong.executor.command.FormDataUpdateServiceFactory;
import com.xbongbong.paas.abstracts.AbstractLowCodeExecuteService;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.data.service.CabinetFileService;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasFormRichTextEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasAttachmentEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.service.dynamic.help.DynamicHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.interfaces.FormDataService;
import com.xbongbong.parent.interfaces.FormDataUpdateService;
import com.xbongbong.pro.cabinetfile.pojo.dto.CabinetFileSaveDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.customercommunicate.pojo.dto.LinkDataDynamicAddDTO;
import com.xbongbong.pro.department.pojo.DepartmentUserPojo;
import com.xbongbong.pro.enums.CabinetFileTypeEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.lowcode.LowCodeExecuteServiceEnum;
import com.xbongbong.pro.formdata.pojo.vo.BeforeSaveVO;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.SaveVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.lowcodeexecute.pojo.dto.LowCodeExecuteServiceDTO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CabinetFileEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderExplainEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.CabinetFileModel;
import com.xbongbong.saas.model.PaasFormRichTextModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.domain.entity.WorkflowBackupRichTextEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.model.WorkflowBackupRichTextModel;
import com.xbongbong.workflow.model.WorkflowTransferDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
@Slf4j
public abstract class AbstractWorkflowDataStrategy {

    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private CabinetFileService cabinetFileService;
    @Resource
    private CabinetFileModel cabinetFileModel;
    @Resource
    private AbstractLowCodeExecuteService abstractLowCodeExecuteService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    @Lazy
    private DynamicHelp dynamicHelp;
    @Resource
    private WorkflowBackupRichTextModel workflowBackupRichTextModel;
    @Resource
    private PaasFormRichTextModel paasFormRichTextModel;
    @Resource
    private WorkflowTransferDataModel workflowTransferDataModel;
    @Resource
    private FormDataServiceFactory formDataServiceFactory;
    @Resource
    private FormDataUpdateServiceFactory formDataUpdateServiceFactory;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;

    /**
     * Description: 文件柜保存
     * @param workflowTransferPOJO
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/7/13 10:32
     * @since
     */
    protected void saveDataCabinetFile(WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        try {
            Data pojoData = workflowTransferPOJO.getData();
            JSONObject data = pojoData.getData();
            Long dataId = pojoData.getId();
            String corpid = workflowTransferPOJO.getCorpid();
            User user = workflowTransferPOJO.getUser();

            Long formId = pojoData.getFormId();
            Integer businessType = pojoData.getBusinessType();
            Integer saasMark = pojoData.getSaasMark();

            Map<String, FieldAttrEntity> explainMap;
            if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
                WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(formId, corpid);
                explainMap = ExplainUtil.getExplainMap(workOrderExplainEntityExt.getExplains(), null);
            } else {
                PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
                explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
            }

            List<String> uploadAttr = new ArrayList<>();
            Set<String> subFormAttr = new HashSet<>();
            Map<String, String> subFormUploadMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (Map.Entry<String, FieldAttrEntity> entry : explainMap.entrySet()) {
                FieldAttrEntity fieldAttrEntity = entry.getValue();
                //启用的并且类型为附件
                List<Integer> subFieldList = Arrays.asList(FieldTypeEnum.SUB_FORM.getType(), FieldTypeEnum.SELECT_PRODUCT.getType());
                if (Objects.equals(fieldAttrEntity.getIsOpen(), 1) && Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())) {
                    uploadAttr.add(fieldAttrEntity.getAttr());
                }
                if (Objects.equals(fieldAttrEntity.getIsOpen(), 1) && subFieldList.contains(fieldAttrEntity.getFieldType())) {
                    //获取子表单内的附件字段
                    List<? extends FieldAttrEntity> fieldAttrEntities = fieldAttrEntity.getSubForm().getItems();
                    for (FieldAttrEntity subFieldEntity : fieldAttrEntities) {
                        if (Objects.equals(subFieldEntity.getIsOpen(), 1) && Objects.equals(subFieldEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())) {
                            subFormAttr.add(fieldAttrEntity.getAttr());
                            subFormUploadMap.put(fieldAttrEntity.getAttr(), subFieldEntity.getAttr());
                        }
                    }
                }
            }

            if (CollectionsUtil.isEmpty(uploadAttr) && subFormUploadMap.isEmpty()) {
                // 没有附件字段，下面的逻辑无需执行
                return;
            }

            List<PaasAttachmentEntityExt> cabinetFileEntities = new ArrayList<>();
            for (String attr : uploadAttr) {
                String uploadStr = data.getString(attr);
                if (Objects.nonNull(uploadStr)) {
                    List<PaasAttachmentEntityExt> filePojos = JSONArray.parseArray(uploadStr, PaasAttachmentEntityExt.class);
                    if (Objects.nonNull(filePojos)) {
                        cabinetFileEntities.addAll(filePojos);
                    }
                }
            }
            //子表单内附件字段上传的文件
            for (String attr : subFormAttr) {
                JSONArray subFormArray = data.getJSONArray(attr);
                if (Objects.nonNull(subFormArray) && !subFormArray.isEmpty()) {
                    for (Object object : subFormArray) {
                        JSONObject jsonObject = (JSONObject) object;
                        String subUploadAttr = subFormUploadMap.get(attr);
                        if (Objects.nonNull(subUploadAttr)) {
                            String subUploadStr = jsonObject.getString(subUploadAttr);
                            if (Objects.nonNull(subUploadStr)) {
                                List<PaasAttachmentEntityExt> subAttachments = JSONArray.parseArray(subUploadStr, PaasAttachmentEntityExt.class);
                                if (Objects.nonNull(subAttachments)) {
                                    cabinetFileEntities.addAll(subAttachments);
                                }
                            }
                        }
                    }
                }
            }


            //去重
            Set<String>  indexSet = new HashSet<>();
            List<PaasAttachmentEntityExt> cabinetFileFilter = new ArrayList<>();
            for (PaasAttachmentEntityExt paasAttachmentEntityExt : cabinetFileEntities) {
                if (!indexSet.contains(paasAttachmentEntityExt.getAttachIndex())) {
                    indexSet.add(paasAttachmentEntityExt.getAttachIndex());
                    cabinetFileFilter.add(paasAttachmentEntityExt);
                }
            }
            // bug-id:37843 edit @date 2021/4/2 10:21 在这里对特殊的回款单，付款单做下转化业务类型，因为文件柜那边传的是回款单和付款单的业务类型，如果存其他的话，在文件柜中无法看见附件；
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
            boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
            if (sheetFlag) {
                businessType = sheetTypeEnum.getXbbRefTypeEnum().getCode();
            }

            List<CabinetFileEntity> cabinetFileDBList;
            if (!Objects.equals(businessType, 0)) {
                //saas
                cabinetFileDBList = cabinetFileModel.getCabinetFiles(corpid, dataId, businessType, CabinetFileTypeEnum.NORMAL.getType(), null);
            } else {
                //paas
                cabinetFileDBList = cabinetFileModel.getCabinetFiles(corpid, dataId, null, CabinetFileTypeEnum.NORMAL.getType(), null);
            }

            Map<String, CabinetFileEntity> cabinetFileEntityMap = new HashMap<>(cabinetFileDBList.size());
            for (CabinetFileEntity entity : cabinetFileDBList) {
                cabinetFileEntityMap.put(entity.getAttachIndex(), entity);
            }
            //需要保留的文件
            List<CabinetFileEntity> keepFileList = new ArrayList<>();
            //新增的需要插入数据的文件
            List<PaasAttachmentEntityExt> insertFileList = new ArrayList<>();
            for (PaasAttachmentEntityExt pojo : cabinetFileFilter) {
                if (cabinetFileEntityMap.containsKey(pojo.getAttachIndex())) {
                    keepFileList.add(cabinetFileEntityMap.get(pojo.getAttachIndex()));
                } else {
                    insertFileList.add(pojo);
                }
            }
            //要删除的文件
            List<CabinetFileEntity> deleteFileList = new ArrayList<>(cabinetFileDBList);
            deleteFileList.removeAll(keepFileList);
            List<Long> deleteIds = new ArrayList<>();
            for (CabinetFileEntity entity : deleteFileList) {
                deleteIds.add(entity.getId());
            }
            //删除文件
            if (deleteIds.size() > 0) {
                cabinetFileModel.deleteBatch(deleteIds, corpid);
            }

            //保存新的文件
            if (insertFileList.size() > 0) {
                Locale locale = LocaleContextHolder.getLocale();
                String lang = locale.toString();
                try{
                    CabinetFileSaveDTO cabinetFileSaveDTO = new CabinetFileSaveDTO(insertFileList, businessType, dataId);
                    cabinetFileSaveDTO.setCorpid(corpid);
                    cabinetFileSaveDTO.setUserId(user.getUserId());
                    cabinetFileSaveDTO.setType(CabinetFileTypeEnum.NORMAL.getType());
                    // 日志需要
                    cabinetFileSaveDTO.setLoginUserName(user.getName());
                    cabinetFileSaveDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    cabinetFileService.saveCabinetFiles(cabinetFileSaveDTO);
                }catch (Exception e){
                    log.error("文件柜保存", e);
                }
            }
        } catch (XbbException e) {
            log.error("com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy.saveDataCabinetFile fail", e);
        }
    }

    /**
     * Description: api回调
     * @param workflowTransferPOJO
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/7/13 15:29
     * @since
     */
    protected void apiHook(WorkflowTransferPOJO workflowTransferPOJO) {
        try {
            Data pojoData = workflowTransferPOJO.getData();
            String corpid = workflowTransferPOJO.getCorpid();

            LowCodeExecuteServiceDTO lowCodeExecuteServiceDTO = new LowCodeExecuteServiceDTO();
            lowCodeExecuteServiceDTO.setAlias(LowCodeExecuteServiceEnum.ADD.name());
            lowCodeExecuteServiceDTO.setBusinessType(pojoData.getBusinessType());
            lowCodeExecuteServiceDTO.setDataId(Collections.singletonList(pojoData.getId()));
            lowCodeExecuteServiceDTO.setFormId(pojoData.getFormId());
            lowCodeExecuteServiceDTO.setSaasMark(pojoData.getSaasMark());
            lowCodeExecuteServiceDTO.setCorpid(corpid);
            List<PaasFormDataEntityExt> list = new ArrayList<>();
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setId(pojoData.getId());
            paasFormDataEntityExt.setDataId(pojoData.getId());
            paasFormDataEntityExt.setData(pojoData.getData());
            paasFormDataEntityExt.setAppId(pojoData.getAppId());
            paasFormDataEntityExt.setMenuId(pojoData.getMenuId());
            paasFormDataEntityExt.setFormId(pojoData.getFormId());
            list.add(paasFormDataEntityExt);
            lowCodeExecuteServiceDTO.setList(list);
            lowCodeExecuteServiceDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            abstractLowCodeExecuteService.execute(lowCodeExecuteServiceDTO);
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy.apiHook fail", e);
        }
    }


    /**
     * 新增后保存日志
     *
     * @param workflowTransferPoJo
     * @throws XbbException
     */
    protected void afterSaveLog(WorkflowTransferPOJO workflowTransferPoJo) throws XbbException {
        Runnable runnable = () -> {
            try{
                //参数拼装
                String corpid = workflowTransferPoJo.getCorpid();
                Integer businessType = workflowTransferPoJo.getData().getBusinessType();
                FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                formDataAddDTO.setCorpid(workflowTransferPoJo.getCorpid());
                formDataAddDTO.setIsImport(workflowTransferPoJo.getIsImport());
                formDataAddDTO.setSaasMark(workflowTransferPoJo.getData().getSaasMark());
                formDataAddDTO.setBusinessType(businessType);
                PaasFormDataEntity newPaasFormDataEntity = new PaasFormDataEntity();
                newPaasFormDataEntity.setSerialNo(workflowTransferPoJo.getData().getData().getString(BasicConstant.SERIAL_NO));
                newPaasFormDataEntity.setData(workflowTransferPoJo.getData().getData());
                UserVO userVO = new UserVO();
                userVO.setName(workflowTransferPoJo.getUser().getName());
                userVO.setUserId(workflowTransferPoJo.getUser().getUserId());
                SaveVO saveVO = new SaveVO();
                if (Objects.equals(workflowTransferPoJo.getData().getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                    WorkOrderEntity workOrderEntity = new WorkOrderEntity();
                    workOrderEntity.setSerialNo(workflowTransferPoJo.getData().getData().getString(BasicConstant.SERIAL_NO));
                    saveVO.setWorkOrderEntity(workOrderEntity);
                }
                BeforeSaveVO beforeSaveVO = new BeforeSaveVO();
                PaasFormExplainEntity explain = proFormHelp.getExplainEntity(corpid, workflowTransferPoJo.getData().getFormId(), businessType);
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explain.getExplains(), null);
                beforeSaveVO.setExplainMap(explainMap);
                saveVO.setDataId(workflowTransferPoJo.getData().getId());
                saveVO.setUserVO(userVO);
                //复用工厂类方法保存新增日志
                FormDataService formDataService = formDataServiceFactory.getFormDataService(businessType, workflowTransferPoJo.getData().getSaasMark());

                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                    WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(workflowTransferPoJo.getData().getFormId(), corpid);
                    beforeSaveVO.setWorkOrderFormEntityExt(workOrderFormEntityExt);
                    formDataService.afterSaveLog(formDataAddDTO, workOrderFormEntityExt, newPaasFormDataEntity, saveVO, beforeSaveVO);
                } else {
                    PaasFormEntityExt paasFormEntityExt = proFormHelp.getPaasFormExt(workflowTransferPoJo.getData().getFormId(), businessType, corpid);

                    beforeSaveVO.setPaasFormEntityExt(paasFormEntityExt);
                    formDataService.afterSaveLog(formDataAddDTO, paasFormEntityExt, newPaasFormDataEntity, saveVO, beforeSaveVO);
                }
            } catch (Exception e){
                log.error("com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy.afterSaveLog fail", e);
            }
        };
        threadPoolBeanConfig.workflowLogThreadPool().execute(runnable);

    }

    /**
     * 更新后保存日志
     *
     * @param workflowTransferPoJo
     * @throws XbbException
     */
    protected void afterUpdateLog(WorkflowTransferPOJO workflowTransferPoJo) throws XbbException {
        Runnable runnable = () -> {
            try {
                //参数拼装
                String corpid = workflowTransferPoJo.getCorpid();
                Integer businessType = workflowTransferPoJo.getOldData().getBusinessType();
                FormDataUpdateDTO formDataUpdateDTO = new FormDataUpdateDTO();
                formDataUpdateDTO.setCorpid(corpid);
                formDataUpdateDTO.setIsCover(workflowTransferPoJo.getIsImport());
                formDataUpdateDTO.setDataId(workflowTransferPoJo.getData().getId());
                formDataUpdateDTO.setSaasMark(workflowTransferPoJo.getData().getSaasMark());
                formDataUpdateDTO.setBusinessType(workflowTransferPoJo.getData().getBusinessType());
                PaasFormDataEntity newPaasFormDataEntity = new PaasFormDataEntity();
                newPaasFormDataEntity.setSerialNo(workflowTransferPoJo.getData().getData().getString(BasicConstant.SERIAL_NO));
                newPaasFormDataEntity.setUpdateTime(workflowTransferPoJo.getData().getData().getLong(StringConstant.UPDATE_TIME));
                newPaasFormDataEntity.setDepartmentId(workflowTransferPoJo.getData().getData().getLong(StringConstant.DEPARTMENT_ID));
                newPaasFormDataEntity.setData(workflowTransferPoJo.getData().getData());
                UserVO userVO = new UserVO();
                userVO.setName(workflowTransferPoJo.getUser().getName());
                userVO.setUserId(workflowTransferPoJo.getUser().getUserId());
                UpdateVO updateVO = new UpdateVO();
                updateVO.setPaasFormDataEntity(newPaasFormDataEntity);
                updateVO.setUserVO(userVO);
                PaasFormExplainEntity explain = proFormHelp.getExplainEntity(corpid, workflowTransferPoJo.getOldData().getFormId(), businessType);
                List<FieldAttrEntity> explainList = JSON.parseArray(explain.getExplains(), FieldAttrEntity.class);
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(explainList, null);
                PaasFormDataEntity oldPaasFormDataEntity = new PaasFormDataEntity();
                if (Objects.nonNull(workflowTransferPoJo.getBackupDataId())){
                    WorkflowBackupDataEntity backupData = workflowBackupDataModel.getByKey(workflowTransferPoJo.getBackupDataId(), corpid);
                    oldPaasFormDataEntity.setSerialNo(backupData.getData().getString(BasicConstant.SERIAL_NO));
                    oldPaasFormDataEntity.setUpdateTime(backupData.getData().getLong(StringConstant.UPDATE_TIME));
                    oldPaasFormDataEntity.setDepartmentId(backupData.getData().getLong(StringConstant.DEPARTMENT_ID));
                    oldPaasFormDataEntity.setData(backupData.getData());
                }
                BeforeUpdateVO beforeUpdateVO = new BeforeUpdateVO();
                beforeUpdateVO.setOldPaasFormData(oldPaasFormDataEntity);
                beforeUpdateVO.setExplainMap(explainMap);
                beforeUpdateVO.setExplainList(explainList);
                //复用工厂类方法保存更新日志
                FormDataUpdateService formDataUpdateService = formDataUpdateServiceFactory.getFormDataUpdateService(businessType, workflowTransferPoJo.getData().getSaasMark());
                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                    WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(workflowTransferPoJo.getOldData().getFormId(), corpid);
                    beforeUpdateVO.setWorkOrderFormEntity(workOrderFormEntityExt);
                    formDataUpdateService.afterSaveLog(formDataUpdateDTO, workOrderFormEntityExt, newPaasFormDataEntity, oldPaasFormDataEntity, updateVO, beforeUpdateVO);
                } else {
                    PaasFormEntityExt paasFormEntityExt = proFormHelp.getPaasFormExt(workflowTransferPoJo.getOldData().getFormId(), businessType, corpid);

                    beforeUpdateVO.setPaasFormEntityExt(paasFormEntityExt);
                    formDataUpdateService.afterSaveLog(formDataUpdateDTO, paasFormEntityExt, updateVO.getPaasFormDataEntity(), oldPaasFormDataEntity, updateVO, beforeUpdateVO);
                }
            } catch (Exception e){
                log.error("com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy.afterUpdateLog fail", e);
            }
        };
        threadPoolBeanConfig.workflowLogThreadPool().execute(runnable);
    }

    protected String getOwnerId(JSONObject data) {
        Object object = data.get(FieldTypeEnum.OWNERID.getAlias());
        if (object instanceof String) {
            return object.toString();
        } else if (object instanceof List) {
            List<DepartmentUserPojo> list = JSON.parseArray(data.getString(FieldTypeEnum.OWNERID.getAlias()), DepartmentUserPojo.class);
            if (CollectionsUtil.isNotEmpty(list)) {
                return list.get(0).getId().toString();
            }
        }
        return null;
    }


    protected Integer updateBackSubForm( PaasFormDataEntity paasFormDataEntity, String corpid, IndexTypeEnum indexTypeEnum) throws XbbException{
        Long id = paasFormDataEntity.getId();
        List<? extends PaasFormSubDataEntity> list = paasFormSubDataModel.getListByIdAndAttr(id, corpid, indexTypeEnum, null);

        paasFormSubDataModel.transferSubForm(paasFormDataEntity, indexTypeEnum);
        Map<Long, PaasFormSubDataEntity> subMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        list.forEach(v -> subMap.put(v.getId(), v));
        List<PaasFormSubDataEntity> updateDataList = new ArrayList<>();
        paasFormDataEntity.getSubFormData().forEach((k, v) -> {
            JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(v, SerializerFeature.DisableCircularReferenceDetect));
            jsonArray.forEach(item -> {
                JSONObject jsonObject = (JSONObject) item;
                Long subDataId = jsonObject.getLong(BusinessConstant.SUB_DATA_ID);
                if (!subMap.containsKey(subDataId) && Objects.nonNull(subDataId)) {
                    // data内id不存储,移除
                    jsonObject.remove(BusinessConstant.SUB_DATA_ID);
                    PaasFormSubDataEntity paasFormSubDataEntity = new PaasFormSubDataEntity();
                    paasFormSubDataEntity.setId(subDataId);
                    paasFormSubDataEntity.setData(jsonObject);
                    paasFormSubDataEntity.setDataId(id);
                    paasFormSubDataEntity.setUpdateTime(DateTimeUtil.getInt());
                    paasFormSubDataEntity.setDel(DelEnum.NORMAL.getDel());
                    updateDataList.add(paasFormSubDataEntity);
                }
            });
        });
        // 更新数据
        return paasFormSubDataModel.updateBatch(updateDataList, indexTypeEnum,corpid);
    }

    /**
     * 不是经销商类型
     * @param workflowTransferPOJO
     * @return
     * @throws XbbException
     */
    protected boolean isNotDistributeBusinessType(WorkflowTransferPOJO workflowTransferPOJO) {
        try {
            Data pojoData = workflowTransferPOJO.getData();
            Long formId = pojoData.getFormId();
            String corpid = workflowTransferPOJO.getCorpid();
            Integer businessType = pojoData.getBusinessType();
            PaasFormExplainEntity paasFormExplainEntity =  new PaasFormExplainEntity();
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(formId, corpid);
                if (Objects.nonNull(workOrderExplainEntityExt)) {
                    BeanUtil.copyProperties(workOrderExplainEntityExt, paasFormExplainEntity);
                }
            } else {
                paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            }
            if (Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), paasFormExplainEntity.getDistributorMark())) {
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy.isNotDistributeBusinessType", e);
            return false;
        }
    }

    //@Async("dynamicThreadPool")
    protected void addLinkDataDynamic(WorkflowTransferPOJO workflowTransferPOJO){
        try {
            LinkDataDynamicAddDTO linkDataDynamicAddDTO = new LinkDataDynamicAddDTO();
            linkDataDynamicAddDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
            linkDataDynamicAddDTO.setNewData(workflowTransferPOJO.getData().getData());
            linkDataDynamicAddDTO.setLoginUserName(workflowTransferPOJO.getUser().getName());
            linkDataDynamicAddDTO.setCorpid(workflowTransferPOJO.getCorpid());
            linkDataDynamicAddDTO.setBusinessType(workflowTransferPOJO.getData().getBusinessType());
            linkDataDynamicAddDTO.setDataId(workflowTransferPOJO.getData().getId());
            linkDataDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            dynamicHelp.addLikData(linkDataDynamicAddDTO);
        }catch (Exception e){
            log.error("com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy.addLinkDataDynamic", e);
        }
    }

    /**
     * 回退被删掉的富文本
     *
     * @param taskId
     * @param workflowTransferPOJO
     */
    protected void updateBackRichText(Long taskId, WorkflowTransferPOJO workflowTransferPOJO){
        //读参数
        Long backupId = workflowTransferPOJO.getBackupDataId();
        String corpid = workflowTransferPOJO.getCorpid();
        Long dataId = workflowTransferPOJO.getData().getId();
        Long formId = workflowTransferPOJO.getData().getFormId();
        Integer businessType = workflowTransferPOJO.getData().getBusinessType();
        Integer saasMark = workflowTransferPOJO.getData().getSaasMark();
        //回退逻辑
        WorkflowBackupRichTextEntity workflowBackupRichTextEntity = workflowBackupRichTextModel.getByBackupId(backupId, corpid);
        PaasFormRichTextEntity paasFormRichTextEntity = new PaasFormRichTextEntity(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL.getDel());
        paasFormRichTextEntity.setData(Objects.isNull(workflowBackupRichTextEntity) ? "" : workflowBackupRichTextEntity.getData());
        paasFormRichTextEntity.setDel(DelEnum.NORMAL.getDel());
        paasFormRichTextModel.updateByDataId(paasFormRichTextEntity);
    }

    /**
     * 拒绝/撤回时删除富文本
     *
     * @param dataId
     * @param corpid
     * @param formId
     * @param businessType
     * @param saasMark
     * @param del
     */
    protected void deleteFormRichText(Long dataId, String corpid, Long formId, Integer businessType, Integer saasMark, DelEnum del){
        PaasFormRichTextEntity entity = new PaasFormRichTextEntity(dataId, corpid, formId, businessType, saasMark, del.getDel());
        paasFormRichTextModel.deleteByDataId(entity);
    }

    /**
     * Description: 补充data中少了的attr key值的data数据，用于编辑数据新增字段数据后，被拒绝后数据还原使用，es的更新需要key值
     * @param sourceObject 来源data
	 * @param targetObject 目标data，需要填充attr的data
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2023/2/23 10:53
     * @since
     */
    protected void replenishAttrForBackupData(JSONObject sourceObject, JSONObject targetObject) {
        proFormHelp.replenishAttrForBackupData(sourceObject, targetObject);

    }
}
